<?php

namespace App\Service;

use App\Http\Controllers\api\PackagesController;
use App\Http\Controllers\api\ParkingController;
use App\Models\BalanceLog;
use App\Models\Commodity;
use App\Models\CommodityOrder;
use App\Models\CustomerSessionInfo;
use App\Models\IntegralLog;
use App\Models\PaymentLog;
use App\Models\RechargeOrder;
use App\Models\RedPacketLog;
use App\Repository\BannersRepository;
use App\Repository\CommodityRepository;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Support\XML;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class WechatService
{
    /**
     * 支付
     * @param $params
     * @return array|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function payment($params)
    {
        $payment = config('payment');
        list($body, $outTradeNo, $totalFee, $notifyUrl, $openId) = $params;
        $app = Factory::payment($payment);
        $params = [
            'body' => $body,
            'out_trade_no' => $outTradeNo,
            'total_fee' => $totalFee,
            'notify_url' => $notifyUrl, // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openId,
        ];
        $result = $app->order->unify($params);
        dd($result);
        if ($result['return_code'] == 'FAIL') {
            return makeResponse([], $result['return_msg'], 500);
        }
        $data = $app->jssdk->bridgeConfig($result['prepay_id']);
        return $data;
    }

    /**
     * 充值回调
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function rechargesCallBack()
    {
//        $request = Request::createFromGlobals();
//        $xml = XML::parse(strval($request->getContent()));
        $payment = config('payment');
        $app = Factory::payment($payment);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            app('log')->debug('payment xml:' . var_export($message, true));
            $type = 2;
            $price = intval($message['total_fee']) / 100;
            $out_trade_no = $message['out_trade_no'];

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    // 充值：修改余额订单状态，余额明细增加一条记录
                    $order = RechargeOrder::where('internal_payment_sn', $out_trade_no)->first();
                    if ($order->order_status != 0) {
                        return true;
                        exit; // 已经做了处理
                    }
                    $order->order_status = 1;
                    $order->save();
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            return true;
            exit;
            // 或者错误消息
//            $fail('Order not exists.');
        });

        return $response; // Laravel 里请使用：return $response;
    }

    /**
     * 购买商品回调
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function shoppingCallBack()
    {
        $payment = config('payment');
        $app = Factory::payment($payment);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            app('log')->debug('payment xml:' . var_export($message, true));
            $type = 1;
            $price = intval($message['total_fee']) / 100;
            $out_trade_no = $message['out_trade_no'];

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    //商品订单：修改订单状态
                    $order = CommodityOrder::where('internal_payment_sn',
                        $out_trade_no)->first();
                    if ($order->order_status != 1) {
                        return true;
                        exit; // 已经做了处理
                    }
                    $order->order_status = 2;
                    $order->pay_type = 2;
                    $order->save();
                    // 记录支付日志
                    $log = PaymentLog::createOne([
                        'internal_payment_sn' => $out_trade_no,
                        'payment_type' => 2,
                        'order_type' => $type
                    ]);
                    $log->save();

                    switch ($order->type) {
                        case 3:
                            // 应急停车
                            $parking = new ParkingController();

                            $result = $parking->finishParkingOrder($order->customer_id, $order);
                            if ($result['code'] == 500) {
                                return $result;
                            }
                            break;
                        case 6:
                            $package = new PackagesController();
                            $result = $package->packageOrder($order->customer_id, $order);
                            if ($result['code'] == 500) {
                                return $result;
                            }
                            break;
                    }

                } elseif (array_get($message, 'result_code') === 'FAIL') {

                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            return true;
            exit;
            // 或者错误消息
//            $fail('Order not exists.');
        });

        return $response; // Laravel 里请使用：return $response;
    }

    /**解密
     * @param $sessionKey
     * @param $encryptedData
     * @param $iv
     * @return bool|string
     */
    public static function decryptData($sessionKey, $encryptedData, $iv)
    {
        /**
         * 3. 解密数据
         * 由于官方的解密方法不兼容 PHP 7.1+ 的版本
         * 这里弃用微信官方的解密方法
         * 采用推荐的 openssl_decrypt 方法（支持 >= 5.3.0 的 PHP）
         * @see http://php.net/manual/zh/function.openssl-decrypt.php
         */
        $aesCipher = base64_decode($encryptedData);
        $skey = base64_decode($sessionKey);
        $aesIV = base64_decode($iv);
        app('log')->debug('data:' . var_export($aesCipher, true));
        app('log')->debug('skey:' . var_export($skey, true));
        app('log')->debug('iv:' . var_export($aesIV, true));

//        $decryptData = \openssl_decrypt(
//            $data,
//            'AES-128-CBC',
//            $skey,
//            OPENSSL_RAW_DATA,
//            $ivEncode
//        );

        try {
            //解密
            $decrypted = openssl_decrypt($aesCipher, 'aes-128-cbc', $skey, OPENSSL_RAW_DATA, $aesIV);
            if ($decrypted === false) {
                throw new \Exception('解密用户信息失败');
            }
        } catch (\Exception $e) {
            return false;
        }

        app('log')->debug('decrypted:' . var_export($decrypted, true));
        return $decrypted;




    }


}
